<template>
  <slot :open="open">
		<el-button type="primary" plain @click="open">导入</el-button>
	</slot>
  <el-dialog v-model="dialogVisible" title="导入" :width="550" :close-on-click-modal="false" append-to-body destroy-on-close>
		<el-progress v-if="loading" :text-inside="true" :stroke-width="20" :percentage="percentage" style="margin-bottom: 15px;" />
		<div v-loading="loading">
			<el-upload ref="uploadRef"
				drag
				:accept="accept"
				:maxSize="maxSize"
				:limit="1"
				:data="data"
				:show-file-list="false"
				:http-request="request"
				:before-upload="beforeUpload"
				:on-progress="progress"
				:on-success="success"
				:on-error="error"
				>
				<slot name="uploader">
					<el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
					<div class="el-upload__text">
						将文件拖到此处或 <em>点击选择文件上传</em>
					</div>
				</slot>
				<template #tip>
					<div class="el-upload__tip">
						<template v-if="tip">{{tip}}</template>
						<template v-else>请上传小于或等于 {{maxSize}}M 的 {{accept}} 格式文件</template>
						<p v-if="templateUrl" style="margin-top: 7px;">
							<el-link :href="templateUrl" target="_blank" type="primary" :underline="false">下载导入模板</el-link>
						</p>
					</div>
				</template>
			</el-upload>
			<el-form v-if="$slots.form" inline label-width="100px" label-position="left" style="margin-top: 18px;">
				<slot name="form" :formData="formData" />
			</el-form>
		</div>
	</el-dialog>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage, ElNotification} from 'element-plus'

// eslint-disable-next-line no-undef
const emits = defineEmits(['success'])
// eslint-disable-next-line no-undef
const props = defineProps({
  apiObj: {type: Object, default: () => {}},
  data: {type: Object, default: () => {}},
  maxSize: {type: Number, default: 10},
  tip: {type: String, default: ''},
  templateUrl: {type: String, default: ''},
  accept: {type: String, default: '.xls, .xlsx'},
})

const uploadRef = ref(null)
const dialogVisible = ref(false)
const loading = ref(false)
const percentage = ref(0)
const formData = ref({})

function open() {
  dialogVisible.value = true
	formData.value = {}
}
function close() {
  dialogVisible.value = false
}
function beforeUpload(file) {
  const p = props
  const maxSize = file.size / 1024 / 1024 < p.maxSize
  if (!maxSize) {
    ElMessage.warning(`上传文件大小不能超过 ${p.maxSize}MB!`)
    return
  }
  loading.value = true
}
function progress(e) {
  percentage.value = e.percent
}
function success(res, file) {
  const uploadRefVal = uploadRef.value
  uploadRefVal.handleRemove(file)
  uploadRefVal.clearFiles()
  loading.value = false
  percentage.value = 0
  emits('success', res, close)
}
function error(err) {
  loading.value = false
  percentage.value = 0
  ElNotification .error({
    title: '上传文件未成功',
    message: err
  })
}
function request(param) {
  const fdata = new FormData()
  const {data, file, filename, onProgress, onSuccess, onError} = param
  Object.assign(data, formData.value)
  
  fdata.append(filename, file)
  for (const key in data) {
    fdata.append(key, data[key])
  }
  props.apiObj.post(fdata, {
    onUploadProgress: e => {
      const complete = parseInt(((e.loaded / e.total) * 100) | 0, 10)
      onProgress({percent: complete})
    }
  }).then(res => {
    onSuccess(res)
  }).catch(err => {
    onError(err)
  })
}
</script>
